//
//  TTDianpuSetViewController.m
//  TaoTuo
//
//  Created by admin on 2019/11/6.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTDianpuSetViewController.h"
#import "TTDianpuTextCellModel.h"
#import "TTDianpuChooseCellModel.h"
#import "TTDianpuSwitchCellModel.h"
#import "TTDianpuImageCellModel.h"
#import "TTDianpuImageViewCell.h"
#import "TTDianpuCommonViewCell.h"

#import "TTDianpuSetHeaderView.h"

#import "TTDianpuManagerModel.h"

#import "AddressView.h"
#import "SPModalView.h"

#import "TTDianpuUploadImageViewController.h"
#import "TTDianpuTemplateViewController.h"
#import "TTCompanyDescribeViewController.h"
#import "TTDianpuDomainViewController.h"

static NSString *textCellID = @"textCellID";
static NSString *imageCellID = @"imageCellID";

@interface TTDianpuSetViewController ()<UITableViewDelegate, UITableViewDataSource, TTDianpuImageViewCellDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) TTDianpuManagerModel *model;

@property (nonatomic, strong) AddressView *addressView;
@property (nonatomic, strong) SPModalView *modalView;
@property (nonatomic, strong) NSArray *shopImagesArray;     // 商城图片urls
@property (nonatomic, strong) NSMutableDictionary *paramsDic;   // 上传的参数

@property (nonatomic, copy) NSString *ShopStyleTemplateId;  // 商城模板id

@end

@implementation TTDianpuSetViewController

- (instancetype)initWithManagerModel:(TTDianpuManagerModel *)managerModel
{
    self = [super init];
    if (self) {
        self.model = managerModel;
        self.ShopStyleTemplateId = self.model.ShopStyleTemplateId;
        self.shopImagesArray = self.model.ShopImageArray;   // 商城图片
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"店铺设置";
    UIButton *rightBarBtn = [UIButton createButtonWithTitle:@"保存" titleColor:kMainColor titleFont:[UIFont systemFontOfSize:15] backgroundColor:nil target:self action:@ selector(saveInfoAction)];
    rightBarBtn.frame = CGRectMake(0, 0, 40, 44);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBarBtn];
    
    [self setupHeaderView];
    [self setupDatas];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTDianpuCellModel *cellModel = self.dataArray[indexPath.row];
    
    if ([cellModel isKindOfClass:[TTDianpuImageCellModel class]]){
        // 图片
        TTDianpuImageViewCell *cell = [tableView dequeueReusableCellWithIdentifier:imageCellID];
        cell.model = (TTDianpuImageCellModel *)cellModel;
        cell.delegate = self;
        return cell;
    } else {
        TTDianpuCommonViewCell *cell = [tableView dequeueReusableCellWithIdentifier:textCellID];
        cell.model = cellModel;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTDianpuCellModel *cellModel = self.dataArray[indexPath.row];
    if ([cellModel isKindOfClass:[TTDianpuImageCellModel class]]){
        // 图片
        [self chooseShopImage:cellModel];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTDianpuCellModel *cellModel = self.dataArray[indexPath.row];
    if ([cellModel isKindOfClass:[TTDianpuImageCellModel class]]) {
        return 130;
    }
    
    return 80;
}

#pragma mark - TTDianpuImageViewCellDelegate
- (void)clickImgCell:(TTDianpuImageViewCell *)imgCell model:(TTDianpuImageCellModel *)model
{
    [self chooseShopImage:model];
}

// 上传填写信息
- (void)saveInfoAction
{
    for (TTDianpuCellModel *model in self.dataArray) {
        if ([model isKindOfClass:[TTDianpuTextCellModel class]]) {
            [self.paramsDic setObject:model.content forKey:model.field];
        } else if ([model isKindOfClass:[TTDianpuChooseCellModel class]]) {
            if ([model.field containsString:@"_"]) {
                
                NSArray *fields = [model.field componentsSeparatedByString:@"_"];
                NSArray *contents = [model.content componentsSeparatedByString:@" "];
                if (contents.count > 1) {
                    [self.paramsDic setObject:contents.firstObject forKey:fields.firstObject];
                    [self.paramsDic setObject:contents[1] forKey:fields[1]];
                    if (contents.count > 2) {
                        [self.paramsDic setObject:contents.lastObject forKey:fields.lastObject];
                    }
                }
                
            } else {
                [self.paramsDic setObject:model.content forKey:model.field];
            }
            
            if ([model.field isEqualToString:@"ShopStyleTemplate"]) {
                [self.paramsDic setObject:self.ShopStyleTemplateId forKey:model.field];
            }
            
        } else if ([model isKindOfClass:[TTDianpuSwitchCellModel class]]) {
            TTDianpuSwitchCellModel *swModel = (TTDianpuSwitchCellModel *)model;
            NSString *str = swModel.on ? @"true" : @"false";
            [self.paramsDic setObject:str forKey:model.field];
        }
    }
    
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:setShopInfoUpload_api parameters:self.paramsDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreashDatas" object:nil];
        [self.navigationController.view makeToast:@"设置成功"];
        [self.navigationController popViewControllerAnimated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

// 选择地址
- (void)chooseCityAction:(TTDianpuChooseCellModel *)senderModel
{
    [self.modalView show];
    // 最后一列的行被点击的回调
    @weakify(self)
    self.addressView.lastComponentClickedBlock = ^(SPProvince *selectedProvince, SPCity *selectedCity, SPDistrict *selectedDistrict) {
        @strongify(self)
        [self.modalView hide];
        
        NSString *areaString = [NSString stringWithFormat:@"%@ %@",selectedProvince.fullname, selectedCity.fullname];
        
        if (selectedDistrict.fullname.length > 0) {
            areaString = [NSString stringWithFormat:@"%@ %@", areaString, selectedDistrict.fullname];
        }
        senderModel.content = areaString;
        [self.tableView reloadRow:[self.dataArray indexOfObject:senderModel] inSection:0 withRowAnimation:UITableViewRowAnimationFade];
    };
}

// 选择商城模板
- (void)chooseShopTemplate:(TTDianpuChooseCellModel *)senderModel
{
    NSInteger index = [self.dataArray indexOfObject:senderModel];
    @weakify(self)
    TTDianpuTemplateViewController *templateVC = [[TTDianpuTemplateViewController alloc] initWithTemplateID:self.ShopStyleTemplateId selectedTemplateIDBlock:^(NSString * _Nonnull selectedID, NSString * _Nonnull templateName) {
        @strongify(self)
        senderModel.content = templateName;
        self.ShopStyleTemplateId = selectedID;
        [self.tableView reloadRow:index inSection:0 withRowAnimation:UITableViewRowAnimationFade];
    }];
    [self.navigationController pushViewController:templateVC animated:YES];
}

// 选择商城图片上传
- (void)chooseShopImage:(TTDianpuCellModel *)senderModel
{
    NSInteger index = [self.dataArray indexOfObject:senderModel];
    TTDianpuUploadImageViewController *uploadVC = [[TTDianpuUploadImageViewController alloc] init];
    uploadVC.imagesArray = self.shopImagesArray;
    // 图片上传完成的回调
    @weakify(self)
    uploadVC.uploadFinishedBlock = ^(NSArray * _Nonnull imageUrlArray) {
        @strongify(self)
        self.shopImagesArray = imageUrlArray;
        TTDianpuCellModel *model;
        if (imageUrlArray.count > 0) {
            model = [TTDianpuImageCellModel setModelWithTitle:@"门店实景图" imageUrlArray:imageUrlArray];
        } else {
            model = [TTDianpuChooseCellModel setModelWithTitle:@"门店实景图" placeholder:@"去上传图片" content:@"" rightImageName:nil target:self selector:@selector(chooseShopImage:) field:@""];
        }
        [self.dataArray replaceObjectAtIndex:index withObject:model];
        [self.tableView reloadRow:index inSection:0 withRowAnimation:UITableViewRowAnimationFade];
    };
    [self.navigationController pushViewController:uploadVC animated:YES];
    
}

// 公司简介
- (void)fillInCompanyProfile:(TTDianpuChooseCellModel *)senderModel
{
    NSInteger index = [self.dataArray indexOfObject:senderModel];
    @weakify(self)
    TTCompanyDescribeViewController *companyVC = [[TTCompanyDescribeViewController alloc] initWithContent:senderModel.content finishBlock:^(NSString *content) {
        @strongify(self)
        senderModel.content = content;
        [self.tableView reloadRow:index inSection:0 withRowAnimation:UITableViewRowAnimationFade];
    }];
    [self.navigationController pushViewController:companyVC animated:YES];
}

// 输入域名
- (void)enterTheDomainName:(TTDianpuChooseCellModel *)senderModel
{
    NSInteger index = [self.dataArray indexOfObject:senderModel];
    @weakify(self)
    TTDianpuDomainViewController *domainVC = [[TTDianpuDomainViewController alloc] initWithDomain:senderModel.content finishBlock:^(NSString *domain) {
        @strongify(self)
        senderModel.content = domain;
        [self.tableView reloadRow:index inSection:0 withRowAnimation:UITableViewRowAnimationFade];
    }];
    [self.navigationController pushViewController:domainVC animated:YES];
}

- (void)setupDatas
{
    [self.dataArray removeAllObjects];
    
    [self.dataArray addObject:[TTDianpuTextCellModel setModelWithTitle:@"商城名称" placeholder:@"请输入商城名称" content:self.model.ShopName field:@"ShopName"]];
    [self.dataArray addObject:[TTDianpuTextCellModel setModelWithTitle:@"联系电话" placeholder:@"请输入商城联系电话" content:self.model.ShopTelephone field:@"ShopTelephone"]];
    
    NSString *city = @"";
    if (self.model.ShopProvince.length > 0 || self.model.ShopCity.length > 0 || self.model.ShopArea.length > 0) {
        city = [NSString stringWithFormat:@"%@ %@ %@", self.model.ShopProvince, self.model.ShopCity, self.model.ShopArea];
    }
    [self.dataArray addObject:[TTDianpuChooseCellModel setModelWithTitle:@"联系地址 省/市/区" placeholder:@"请选择门店所在省/市/区" content:city rightImageName:@"无图片" target:self selector:@selector(chooseCityAction:) field:@"ShopProvince_ShopCity_ShopArea"]];
    [self.dataArray addObject:[TTDianpuTextCellModel setModelWithTitle:@"联系地址 街道" placeholder:@"请输入门店街道地址" content:self.model.ShopAddress field:@"ShopAddress"]];
    [self.dataArray addObject:[TTDianpuChooseCellModel setModelWithTitle:@"商城模板" placeholder:@"请选择商城模板" content:self.model.ShopStyleTemplateName rightImageName:nil target:self selector:@selector(chooseShopTemplate:) field:@"ShopStyleTemplate"]];
    
    if (self.model.ShopImageArray.count > 0) {
        [self.dataArray addObject:[TTDianpuImageCellModel setModelWithTitle:@"门店实景图" imageUrlArray:self.model.ShopImageArray]];
    } else {
        [self.dataArray addObject:[TTDianpuChooseCellModel setModelWithTitle:@"门店实景图" placeholder:@"去上传图片" content:@"" rightImageName:nil target:self selector:@selector(chooseShopImage:) field:@""]];
    }
    
    [self.dataArray addObject:[TTDianpuChooseCellModel setModelWithTitle:@"公司简介" placeholder:@"请完善公司简介" content:self.model.ShopDescribes rightImageName:nil target:self selector:@selector(fillInCompanyProfile:) field:@"ShopDescribes"]];
    [self.dataArray addObject:[TTDianpuChooseCellModel setModelWithTitle:@"公司自有域名" placeholder:@"请输入域名" content:self.model.ShopDomainName2 rightImageName:nil target:self selector:@selector(enterTheDomainName:) field:@"ShopDomainName"]];
    
    TTDianpuSwitchCellModel *flagModel = [TTDianpuSwitchCellModel setModelWithTitle:@"技术支持标识" placeholder:@"是否显示" content:@"是否显示" isOn:self.model.ShopTechSupport clickSwitchBlock:^(TTDianpuSwitchCellModel * _Nullable switchModel) {
        NSLog(@"点击了开关 == %d", switchModel.on);
//        [self.tableView reloadRow:self.dataArray.count - 1 inSection:0 withRowAnimation:UITableViewRowAnimationFade];
    } field:@"ShopTechSupport"];
    [self.dataArray addObject:flagModel];
    
    [self.tableView reloadData];
    
}

- (void)setupHeaderView
{
    TTDianpuSetHeaderView *headerView = [TTDianpuSetHeaderView headerViewWithLogo:self.model.ShopLogo erWeiMa:self.model.ShopWeChatQRCode bgUrlString:self.model.ShopBackgroundImg upLoadResult:^(NSMutableDictionary * _Nonnull dic) {
        // 得到上传图片的地址的字典
        [self.paramsDic addEntriesFromDictionary:dic];
    }];
    
    self.tableView.tableHeaderView = headerView;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 50;
        _tableView.emptyImageName = @"nodata";
        _tableView.emptyTitel = @"暂无数据";
        _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TTDianpuCommonViewCell class]) bundle:nil] forCellReuseIdentifier:textCellID];
        [_tableView registerClass:[TTDianpuImageViewCell class] forCellReuseIdentifier:imageCellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
    }
    return _tableView;
}



- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (SPModalView *)modalView
{
    if (!_modalView) {
        _modalView = [[SPModalView alloc] initWithView:self.addressView inBaseViewController:self];
        _modalView.narrowedOff = YES;
    }
    return _modalView;
}

- (AddressView *)addressView {
    
    if (!_addressView) {
        _addressView = [[AddressView alloc] init];
        _addressView.frame = CGRectMake(0, 0, kScreenWidth, 400);
        _addressView.topLabel.text = @"请选择联系地址";
        NSString *path = [[NSBundle mainBundle] pathForResource:@"area.plist" ofType:nil];
        NSArray *arr = [NSArray arrayWithContentsOfFile:path];
        _addressView.datas = arr;
    }
    return _addressView;
}

- (NSMutableDictionary *)paramsDic
{
    if (!_paramsDic) {
        _paramsDic = [NSMutableDictionary dictionary];
    }
    return _paramsDic;
}


@end
